/**
 * 
 */
package GUI.main;


import officeserver.log_error.OfficeException;
import officeserver.log_error.UserException;
import officeserver.office.Calendar;
import officeserver.office.Office;
import officeserver.users.AccessLevel;
import officeserver.users.UserList;

import GUI.calendar.CalendarPanel;
import GUI.main.dialogs.LoginDialog;

/**
 * @author mramsey3
 * 
 */
public class MainClient {

    private static Office officeConnection;
    private static MainFrame mf;
    private static LoginDialog ld;

    /**
     * @param args
     */
    public static void main(String[] args) {
	getLogin().setVisible(true);
	getLogin().setModal(true);
	waitForLogin();
	System.out.println("Logged In!");
	initializeMF();
    }

    /**
     * @return
     */
    public static MainFrame getMainFrame() {
	if (mf == null) {
	    mf = new MainFrame();
	}
	return mf;
    }

    /**
     * @return
     */
    public static LoginDialog getLogin() {
	if (ld == null) {
	    ld = new LoginDialog();
	}
	return ld;
    }

    /**
     * 
     */
    public static void logOut() {
	getConnection().userLogout();
	getMainFrame().setVisible(false);
	getLogin().setVisible(true);
	getLogin().setModal(true);
	waitForLogin();
	initializeMF();
    }

    /**
     * 
     */
    public static void initializeMF() {
	getMainFrame().getNavigationMenuPanel().initialize();
	getMainFrame().pack();
	getMainFrame().setVisible(true);
	getMainFrame().getCalendarPanel().getMonthComboBox().setSelectedIndex(
		CalendarPanel.getCurrentMonth());
    }

    /**
     * 
     */
    public static void waitForLogin() {
	try {
	    while (!getConnection().isLoggedIn()) {
		System.out.print("");
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    /**
     * @return
     */
    public static Office getConnection() {
	if (officeConnection == null) {

	    officeConnection = new Office();
	    try {
		officeConnection.load();
	    } catch (OfficeException e) {
		UserList.clear();
		try {
		    UserList.addUser("admin", "admin", "admin", "admin1",
			    AccessLevel.ADMIN);
		    UserList.addUser("doctor", "doctor", "doctor", "doctor1",
			    AccessLevel.DOCTOR);
		    UserList.addUser("patient", "patient", "patient",
			    "patient1", AccessLevel.PATIENT);
		    UserList.addUser("nurse", "nurse", "nurse", "nurse1",
			    AccessLevel.NURSE);
		    Calendar.discoverNewDoctor();
		} catch (UserException e1) {
		    e1.printStackTrace();
		}
	    }
	    System.out.println("Starting up the server.");
	}
	return officeConnection;
    }

}
